/*
 * Copyright (C) 2010-2014 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package trs.wmata.api;

import static trs.wmata.api.Util.getLname;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public abstract class ApiResponse extends DefaultHandler {
    private int responseCode = -500;
    private String responseMessage = "";
    private final StringBuilder buff = new StringBuilder();

    public boolean hasError() {
        return (responseCode < 0) || (responseCode >= 400);
    }

    @Override
    public final void characters(final char[] ch, final int start, final int length) {
        if (doCaptureChars()) {
            buff.append(ch, start, length);
        }
    }

    public boolean doCaptureChars() {
        return true;
    }

    @Override
    public final void endElement(final String uri, final String name, final String qName) {
        final String lName = getLname(name, qName);
        // System.out.println(lName + ":" + buff);
        endElement(lName, buff);
    }

    public abstract void endElement(final String lName, final StringBuilder buff);

    @Override
    public final void startElement(final String uri, final String name, final String qName, final Attributes atts) {
        final String lName = getLname(name, qName);
        startElement(lName, atts);

        buff.delete(0, buff.length());
    }

    public void startElement(final String lName, final Attributes atts) {
        throw new IllegalStateException("Method Not Implemented");
    }

    public int getResponseCode() {
        return responseCode;
    }

    public boolean isResponseOk() {
        return getResponseCode() == 200;
    }

    public void setResponseCode(final int responseCode) {
        this.responseCode = responseCode;
    }

    public String getResponseMessage() {
        return responseMessage;
    }

    public void setResponseMessage(final String responseMessage) {
        this.responseMessage = responseMessage;
    }

    protected double toDouble(final String str, final double def) {
        try {
            return Double.valueOf(str);
        } catch (final NumberFormatException e) {
            return def;
        }
    }

    protected int toInteger(final String str, final int def) {
        try {
            return Integer.valueOf(str);
        } catch (final NumberFormatException e) {
            return def;
        }
    }
}
